<template>
  <a-modal
    :visible="visible"
    okText="提交"
    cancelText="关闭"
    :title="title"
    :destroyOnClose="true"
    :maskClosable="false"
    :keyboard="false"
    width="800px"
    @cancel="closeModal()"
    :confirmLoading="confirmLoading"
    @ok="handleSubmit"
  >
    <a-form :form="form" :label-col="{ span: 5 }" :wrapper-col="{ span: 14 }">
      <a-form-item label="地址名称">
        <a-input
          :maxLength="50"
          v-decorator="[
            'addressName',
            { rules: [{ required: true, message: '请填写地址名称' }] },
          ]"
          placeholder="请填写地址名称"
        />
      </a-form-item>
      <a-form-item label="地址类型">
        <a-select
          allowClear
          :options="addressTypeOptions"
          placeholder="请选择地址类型"
          v-decorator="[
            'addressType',
            { rules: [{ required: true, message: '请选择地址类型' }] },
          ]"
        />
      </a-form-item>
      <a-form-item label="联系人姓名">
        <a-input
          :maxLength="16"
          v-decorator="[
            'contactName',
            { rules: [{ required: true, message: '请填写联系人姓名' }] },
          ]"
          placeholder="请填写联系人姓名"
        />
      </a-form-item>
      <a-form-item label="所在区域" :help="addressHelp">
        <a-cascader
          :field-names="{
            label: 'areaName',
            value: 'id',
            children: 'children',
          }"
          :options="areaTree"
          :show-search="true"
          placeholder="请选择所属区域"
          v-decorator="[
            'areaIdList',
            { rules: [{ required: true, message: '请选择所属区域' }] },
          ]"
        />
      </a-form-item>
      <a-form-item label="详细地址">
        <a-textarea
          :maxLength="100"
          v-decorator="[
            'address',
            { rules: [{ required: true, message: '请填写详细地址' }] },
          ]"
          placeholder="请输入详细地址信息，如道路、门牌号、小区、楼栋号、单元等信息"
        />
      </a-form-item>
      <a-form-item label="联系电话" help="支持输入手机号或者座机号码，座机格式例如：xxxx-xxxxxxxx">
        <a-input
          :maxLength="13"
          type="tel"
          v-decorator="[
            'phone',
            {
              rules: [
                { required: true, message: '请填写联系电话' },
                {
                  pattern: /^((\d{3,4}-\d{7,8})|(1[3,4,5,6,7,8,9]\d{9}))$/,
                  message: '请填写正确的联系电话',
                },
              ],
            },
          ]"
          placeholder="请填写联系电话"
        />
      </a-form-item>
    </a-form>
  </a-modal>
</template>
<script>
import { getAreaTree } from "@/utils/asyncUtils";
import { treeFindPath } from "@/utils";
import { createOptionsByDict } from '@/utils/dict'
import zip from "lodash/zip";
export default {
  name: "address-info",
  props: {
    record: {
      type: Object,
      default() {
        return {};
      },
    },
    visible: {
      type: Boolean,
      default: false,
    },
  },
  computed: {
    title() {
      return this.record.id ? "修改地址" : "添加地址";
    },
  },
  data() {
    return {
      form: this.$form.createForm(this, { name: "coordinated" }),
      addressTypeOptions: createOptionsByDict('ADDRESS_TYPE'),
      areaTree: [],
      confirmLoading: false,
      addressHelp: '正在获取地区信息，请稍等...',
    };
  },
  watch: {
    visible(value) {
      if (value) {
        if (!(this.areaTree && this.areaTree.length)) {
          this.addressHelp = '正在获取地区信息，请稍等...'
          getAreaTree().then((res) => {
            this.areaTree = res;
            this.addressHelp = ''
          });
        }
        if (this.record.id) {
          this.getAddressInfo();
        }
      }
    },
  },
  mounted() {},
  methods: {
    getAddressInfo() {
      this.$get("/address/config/id", { id: this.record.id }).then((res) => {
        if (res && res.returnCode === 1000) {
          const record = res.dataInfo;
          record.areaIdList = [
            record.provinceCode,
            record.cityCode,
            record.areaCode,
            record.streetCode,
          ].filter((item) => item);
          this.$nextTick(() => {
            const formItems = this.form.getFieldsValue();
            Object.keys(formItems).forEach((key) => {
              formItems[key] = record[key];
            });
            this.form.setFieldsValue(formItems);
          });
        }
      });
    },
    getAreaSubmitInfo(areaIdList = []) {
      const lastId = areaIdList[areaIdList.length - 1];
      const areaNameList = treeFindPath(
        this.areaTree,
        (data) => lastId == data.id,
        [],
        "areaName"
      );
      const areaList = zip(areaIdList, areaNameList); // 返回 [[省id, 省name], [市id, 市name], [区id, 区name], [街道id, 街道name]]
      const areaInfo = {
        provinceCode: (areaList[0] && areaList[0][0]) || "",
        province: (areaList[0] && areaList[0][1]) || "",
        cityCode: (areaList[1] && areaList[1][0]) || "",
        city: (areaList[1] && areaList[1][1]) || "",
        areaCode: (areaList[2] && areaList[2][0]) || "",
        area: (areaList[2] && areaList[2][1]) || "",
        streetCode: (areaList[3] && areaList[3][0]) || "",
        street: (areaList[3] && areaList[3][1]) || "",
        treePath: `0,${areaIdList.join(',')}`,
      };

      return areaInfo;
    },
    
    handleSubmit() {
      this.confirmLoading = true;
      this.form.validateFields((err, values) => {
        if (!err) {
          let url = "/address/config/add";
          console.log(this.record);
          if (this.record.id) {
            url = "/address/config/update";
          }
          const areaInfo = this.getAreaSubmitInfo(values.areaIdList);
          delete values.areaIdList;
          values.fullAddress =
            areaInfo.province +
            areaInfo.city +
            areaInfo.area +
            areaInfo.street +
            values.address;
          this.$post(url, { ...values, ...areaInfo, id: this.record.id })
            .then((res) => {
              this.confirmLoading = false;
              if (res && res.returnCode === 1000) {
                this.$message.success("保存成功！");
                this.closeModal(true);
              }
            })
            .catch((err) => {
              this.confirmLoading = false;
            });
        } else {
          this.confirmLoading = false;
        }
      });
    },

    closeModal(freshTable) {
      this.form.resetFields();
      this.$emit("cancel", freshTable);
    },
  },
};
</script>